package com.nidu.demo.permission.service;

import cn.hutool.core.collection.CollUtil;
import com.nidu.demo.common.enums.DataScopeEnum;
import com.nidu.demo.dept.gateway.DepartmentGateway;
import com.nidu.demo.role.gateway.RoleGateway;
import com.nidu.demo.role.model.Role;
import com.nidu.demo.user.gateway.UserDepartmentGateway;
import com.nidu.demo.user.gateway.UserRoleGateway;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 数据权限服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DataPermissionServiceImpl implements DataPermissionService {

    private final UserRoleGateway userRoleGateway;
    private final RoleGateway roleGateway;
    private final UserDepartmentGateway userDepartmentGateway;
    private final DepartmentGateway departmentGateway;

    @Override
    public DataScopeEnum getUserDataScope(Long userId) {
        // 获取用户的角色
        Set<Long> roleIds = userRoleGateway.getRoleIdsByUserId(userId);
        if (CollUtil.isEmpty(roleIds)) {
            // 如果没有角色，默认只能查看自己的数据
            return DataScopeEnum.SELF;
        }

        // 查询角色的数据权限范围，取最大权限
        return roleGateway.getByIds(roleIds).stream()
                .map(role -> DataScopeEnum.of(role.getDataScope()))
                .max((scope1, scope2) -> Integer.compare(scope1.getValue(), scope2.getValue()))
                .orElse(DataScopeEnum.SELF);
    }

    @Override
    public Set<Long> getUserAccessibleDeptIds(Long userId, DataScopeEnum dataScope) {
        Set<Long> deptIds = new HashSet<>();
        
        switch (dataScope) {
            case SELF:
                // 仅本人数据权限，在拦截器中会添加用户ID限制
                break;
            case DEPT_CUSTOM:
                // 自定义部门数据权限，需要查询角色配置的部门
                Set<Long> roleIds = userRoleGateway.getRoleIdsByUserId(userId);
                deptIds = roleGateway.getByIds(roleIds).stream().map(Role::getDataScopeDeptIds).filter(Objects::nonNull).flatMap(Set::stream).collect(Collectors.toSet());
                break;
            case DEPT_ONLY:
                // 部门数据权限，只能查看所在部门的数据
                deptIds = userDepartmentGateway.getDeptIdsByUserId(userId);
                break;
            case DEPT_AND_CHILD:
                // 部门及以下数据权限，包括所在部门及其子部门
                Set<Long> userDeptIds = userDepartmentGateway.getDeptIdsByUserId(userId);
                for (Long deptId : userDeptIds) {
                    deptIds.add(deptId);
                    deptIds.addAll(departmentGateway.getAllChildrenIds(deptId));
                }
                break;
            case ALL:
                // 全部数据权限，返回空集合（在拦截器中不添加部门限制）
                break;
            default:
                log.warn("未知的数据权限范围: {}", dataScope);
                break;
        }
        
        return deptIds;
    }
}